package com.shelpe.services.tenant.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.ansj.domain.Result;
import org.ansj.domain.Term;
import org.ansj.splitWord.analysis.ToAnalysis;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.shelpe.services.tenant.model.Products;
import com.shelpe.services.tenant.mongomodel.AdRecommendWord;
import com.shelpe.services.tenant.proxy.RecommendClient.RecommendWord;
import com.shelpe.services.tenant.service.CoreWordService;
import com.shelpe.services.tenant.service.RecommendWordService;
import com.shelpe.services.tenant.util.WordInfo;


@Service
public class CoreWordServiceImpl implements CoreWordService{
	
	private static final Logger logger = LoggerFactory.getLogger(CoreWordServiceImpl.class);
	
	@Autowired
	private RecommendWordService recommendWordService;
	
	@Override
	public boolean isCoreWord(String word, Products product){
		
		return filterBySimilarity(word, product.getTitle());
	}
	
	@Override
	public JSONArray getCoreWordFromRecommendWord(List<RecommendWord> reWord){

		if(reWord == null || reWord.size() == 0){
			return null;
		}
		
		Map<String, Integer> map = new HashMap<String, Integer>();
		
		for(RecommendWord item : reWord){
			String word = item.getWord();
			Result result = null;
			
			try{
				//logger.info("before seg {}", word);
				result = ToAnalysis.parse(word);
				//logger.info("after seg {}", result);
			}catch(Exception e){
				logger.info("getCoreWordFromRecommendWord somthing is wrong {}", e);
			}
			 
			if(result == null){
				continue;
			}
			
			Iterator<Term> it = result.iterator();
			//Term preItem = null;
			Term currItem = null;
			while(it.hasNext()){
				//preItem = currItem;
				currItem = it.next();
				//String preName = null;
				//if(preItem != null){
				//	preName = preItem.getName();
				//}
				
				//String currName = currItem.getName();
				String segWord = currItem.getName();
				//if(preName != null && (preName.length() == 1 || currName.length() == 1)){
					//if(!preName.equals(" ") && !currName.equals(" ")){
						//segWord = preName + currName;
					//}
				//}
				
				if(!segWord.equals(" ")){
					
					Integer value = map.get(segWord);
					if(value != null){
						value = value + 1;
					}else{
						value = 1;
					}
					map.put(segWord, value);
				}
			}
		}

		return getSubFreqWords(map);
	}
	
	@Override
	public List<RecommendWord> getKeywordByRecommand(String nick, Long adgroupId){
		
		//AdRecommendWord adre = recommendWordService.getRecommendWord(adgroupId);
		AdRecommendWord adre = recommendWordService.getRecommendWordFromProxy(nick, adgroupId);
		
		if(adre != null){
			recommendWordService.saveRecommendWord(adre);
		}else{
			logger.info("getKeywordByRecommand can not get info from proxy");
			return null;
		}
		
		return adre.getWord();
	}
	
	private boolean filterBySimilarity(String word, String title){
		
		if(word == null || title == null){
			return false;
		}
		logger.info("filterBySimilarity word: {}, title: {}", word, title);
		char[] chWord = word.toCharArray();
		char[] chTitle = title.toCharArray();
		int sim = 0;
		
		for(int i = 0; i < chWord.length; i++){
			for(int j = 0; j < chTitle.length; j++){
				if(chWord[i] == chTitle[j]){
					sim++;
				}
			}
		}
		logger.info("filterBySimilarity sim {}, chWord len {}", sim, chWord.length);
		return sim/(chWord.length + 0.001) > 0.7;
	}
	
	private String getMaxFreqWord(Map<String, Integer> map){
		
		int maxFreq = 0;
		String result = null;
		for(Map.Entry<String, Integer> entry : map.entrySet()){
			
			if(maxFreq < entry.getValue()){
				maxFreq = entry.getValue();
				result = entry.getKey();
			}
		}
		
		return result;
	}
	
	private JSONArray getSubFreqWords(Map<String, Integer> map){
		
		List<WordInfo> wordList = new ArrayList<WordInfo>();

		for(Map.Entry<String, Integer> entry : map.entrySet()){
			WordInfo word = new WordInfo();
			word.setWord(entry.getKey());
			word.setFreq(entry.getValue());
			
			wordList.add(word);
		}
		
		Collections.sort(wordList, new Comparator<WordInfo>(){

			@Override
			public int compare(WordInfo o1, WordInfo o2) {
				// TODO Auto-generated method stub
				int freq1 = o1.getFreq();
				int freq2 = o2.getFreq();
				return freq1 == freq2 ? 0 : (freq1 < freq2 ? 1 : -1);
			}		
		});
		
		int size = wordList.size() > 3 ? 3 : wordList.size();//取出现频率最大的三个
		JSONArray subList = new JSONArray();
		
		for(int i = 0; i < size; i++){
			subList.add(wordList.get(i).getWord());
		}
		
		return subList;
	}
	
}
